<template>
  <el-card>
    <div class="mb-20px">
      <h4>{{ id === -1 ? '新增' : '编辑' }}</h4>
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
    >
      <el-form-item label="轮播图名称" prop="carouselName">
        <el-input v-model="formData.carouselName" placeholder="请输入轮播图名称" />
      </el-form-item>
      <el-form-item label="显示顺序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入显示顺序" type="number" min="0" />
      </el-form-item>
      <el-form-item label="上传图片" prop="imagePath">
        <div class="flex items-end">
          <UploadImg v-model="formData.imagePath" /><span class="ml-10px">1080px*1920px</span>
        </div>
      </el-form-item>
      <el-form-item label="显示状态" prop="status">
        <el-switch v-model="formData.status" :active-value="0" :inactive-value="1" />
      </el-form-item>
      <el-form-item label="展示位置" prop="displayLocation">
        <el-select
          v-model="formData.displayLocation"
          placeholder="请选择"
          clearable
          class="!w-240px"
        >
          <el-option label="首页顶部" :value="0" />
          <el-option label="首页中部" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="跳转路径" prop="jumpPath">
        <el-select v-model="formData.jumpPath" placeholder="请选择" clearable class="!w-240px">
          <el-option
            v-for="i in columnTypeList"
            :key="i.id"
            :label="i.columnName"
            :value="i.id + ''"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跳转对象" prop="jumpId">
        <el-input v-model="formData.jumpId" placeholder="请输入跳转对象ID" />
      </el-form-item>
    </el-form>
    <div>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button
        @click="
          () => {
            $router.back()
            delVisitedView(route)
          }
        "
        >取 消</el-button
      >
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { CarouselImageApi, CarouselImage } from '@/api/biz/carouselimage'
import { ColumnTypeApi, ColumnType } from '@/api/biz/columntype'
import { useTagsViewStore } from '@/store/modules/tagsView'

const { delVisitedView } = useTagsViewStore()
const route = useRoute()
const router = useRouter()

/** 轮播图 表单 */
defineOptions({ name: 'CarouselImageForm' })
const id = +useRoute().params.id

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const columnTypeList = ref<ColumnType[]>([]) // 列表的数据

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  carouselName: undefined,
  sort: undefined,
  displayLocation: 0,
  status: 0,
  jumpPath: undefined,
  jumpId: undefined,
  imagePath: undefined
})
const formRules = reactive({
  carouselName: [{ required: true, message: '轮播图名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
  displayLocation: [{ required: true, message: '展示位置不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '显示状态不能为空', trigger: 'blur' }],
  imagePath: [{ required: true, message: '图片不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CarouselImageApi.getCarouselImage(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CarouselImage
    if(!data.jumpPath) data.jumpPath=null
    if(!data.jumpId) data.jumpId=null
    if (formType.value === 'create') {
      await CarouselImageApi.createCarouselImage(data)
      message.success(t('common.createSuccess'))
    } else {
      await CarouselImageApi.updateCarouselImage(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    router.back()
    delVisitedView(route)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    carouselName: undefined,
    sort: undefined,
    displayLocation: 0,
    status: 0,
    jumpPath: undefined,
    jumpId: undefined,
    imagePath: undefined
  }
  formRef.value?.resetFields()
}

ColumnTypeApi.getColumnTypePage({ page: 1, pageSize: 100 }).then((data) => {
  columnTypeList.value = data.list
})

open(id === -1 ? 'create' : 'update', id === -1 ? undefined : id)
</script>
